﻿using CarparkBusiness;
using CarparkEnum;
using CarparkIMS_CMS.Extensions;
using CarparkIMS_CMS.Models;
using CarparkIMS_Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Quartz.Impl.AdoJobStore.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CarparkIMS_CMS.Controllers
{
    public class HomeController : Controller
    {
        private readonly IMSContext context;
        private readonly ILogger<HomeController> _logger;

        public IServiceProvider Services { get; }
        public ParkingSettingX  ParkingSetting { get; set; }
        public IOptions<ParkingSettingX> ParkingSettingOption { get; set; }
        public HomeController(IMSContext iMSContext, IServiceProvider services, ILogger<HomeController> logger,IOptions<ParkingSettingX> parkingSetting)
        {
            context = iMSContext;
            Services = services;
            _logger = logger;
            ParkingSetting = parkingSetting.Value;
            ParkingSettingOption = parkingSetting;
        }
        [Authorize(AuthenticationSchemes = Startup.AuthSchemes)]
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }
        [HttpGet]
        public async Task<IActionResult> StopBackGround()
        {
            Worker._CancelSource = new CancellationTokenSource(1000);
             
            BackgroundServiceStatus bgService = BackgroundServiceStatus.Get();

            bgService.IsStopped = !bgService.IsStopped;
            bgService.StoppedOn = DateTime.Now;
            BackgroundServiceStatus.Save(bgService);
            ViewBag.BackgroundServiceStatus = bgService;
            string msg = bgService.IsStopped ? "SUCCESS - SERVICE STOPPED" : "SUCCESS - IN SERVICE";
            _logger.LogInformation($"[FUNC::Home:StopBackGround] [BACKGROUND SERVICE {msg} STOP={bgService.IsStopped}  {bgService.StoppedOn:yyyy-MM-ddTHH:mm:ss} ");
             
            ResponseModalX responseModalX = new ResponseModalX { 
                    meta = new MetaModalX { ErrorCode = (int)GeneralReturnCode.SUCCESS ,Success = true, Message = msg },
                    data = bgService
            };  
            await Task.Delay(2000);
            return Ok(responseModalX);
        }

        [HttpGet]
        [Route("[controller]/[action]/{id}")]
        public async Task<IActionResult> ParkinngPlaceChange(int id)
        {
            var cDoorMap = context.llqqCameraDoorMapping.Find(id); 
            cDoorMap.Deleted = !cDoorMap.Deleted;
              
            string msg = cDoorMap.Deleted ? "OUT OF SERVICE" : "IN SERVICE"; 
            _logger.LogInformation($"[FUNC::Home:ParkinngPlaceChange] [SUCCESS - {msg} STATUS={cDoorMap.Deleted}");

            context.llqqCameraDoorMapping.Update(cDoorMap);
            bool res =  await context.SaveChangesAsync() > 0;

            ResponseModalX responseModalX = new ResponseModalX
            {
                meta = new MetaModalX { ErrorCode = (int)GeneralReturnCode.SUCCESS, Success = res, Message = msg },
                data = cDoorMap
            };
            await Task.Delay(2000);
            return Ok(responseModalX);
        }

        [HttpGet]
        public async Task<IActionResult> StopWorkerService()
        {
            ResponseModalX responseModalX = new ResponseModalX
            {
                meta = new MetaModalX { ErrorCode = (int)GeneralReturnCode.SUCCESS, Success = true, Message = "Woker Service Stopped!!!" }
            }; 
            await Task.Delay(1);
            //var worker = Services.GetService<Worker>(); 
            var hostService = Services.CreateScope().ServiceProvider
                              .GetService<IHostedService>();

            CancellationToken cancellation = new CancellationToken(true);
            await hostService.StopAsync(cancellation);
            return Ok(responseModalX);
        }
        //StopScopedService
        [HttpGet]
        public async Task<IActionResult> StopScopedService()
        {
            ResponseModalX responseModalX = new ResponseModalX
            {
                meta = new MetaModalX { ErrorCode = (int)GeneralReturnCode.SUCCESS, Success = true, Message = "Scoped Service Stopped!!!" }
            };
            await Task.Delay(1);
          
            var scopedService = Services.CreateScope().ServiceProvider
                              .GetService<IHostedService>();

            CancellationToken cancellation = new CancellationToken(true);
            await scopedService.StopAsync(cancellation);
            return Ok(responseModalX);
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    } 
}
